package newapp.dob.com.dc_new_app;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import newapp.dob.com.dc_new_app.api.Api;
import newapp.dob.com.dc_new_app.api.bean.DealMoneyBean;
import newapp.dob.com.dc_new_app.api.bean.OrderListModel;
import newapp.dob.com.dc_new_app.api.bean.UploadImageBean;
import newapp.dob.com.dc_new_app.base.BaseActivity;
import newapp.dob.com.dc_new_app.util.Base64;
import newapp.dob.com.dc_new_app.util.RxLifeUtil;
import newapp.dob.com.dc_new_app.util.Spans;
import newapp.dob.com.dc_new_app.util.UI;
import newapp.dob.com.dc_new_app.view.LastInputEditText;
import newapp.dob.com.dc_new_app.view.SlowScrollView;

/**
 * Created by xsooy-pc on 2017/8/24.
 */

public class TakeMoneySureActivity extends BaseActivity {
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.take_view)
    LinearLayout takeView;
    @BindView(R.id.txt_order)
    LastInputEditText txtOrder;
    @BindView(R.id.txt_pay_money)
    EditText txtPayMoney;
    @BindView(R.id.repay_tip)
    TextView repayTip;
    @BindView(R.id.repay_tip_right)
    TextView repayTipRight;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.layout_total)
    LinearLayout layoutTotal;
    @BindView(R.id.scrollView)
    SlowScrollView scrollView;
    @BindView(R.id.repay_tip_new_right)
    TextView repayTipNewRight;
    private OrderListModel.DataBean.ListsBean item;
    private String imgUrl;
    private InputMethodManager imm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_money_sure);
        ButterKnife.bind(this);
        initBar();
//        txtPayMoney.requestFocus();
//        showSoftInputFromWindow(this, txtPayMoney);

        item = getIntent().getParcelableExtra("data");
        if (item == null) {
            return;
        }
        repayTip.setText("账单总额   " + item.repay_money);
        repayTipRight.setText("余额抵扣   " + item.offset_money);
        txtPayMoney.setText(item.order_money);
        number.setText("优惠券   " + item.coupon_money);
        repayTipNewRight.setText("待支付金额   " + item.order_money);
//        txtOrder.setText(item.notice_sn);

        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        Spanned sss = Spans.with(this).font("测试一下", getResources().getDimensionPixelSize(R.dimen.x30)).font("测试一下", getResources().getDimensionPixelSize(R.dimen.x34), 0xFFcacaca).build();
//        txtOrder.setText(sss);
    }


    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, 0x1);
    }

    @OnClick({R.id.left_img, R.id.btn_copy_text, R.id.take_view, R.id.submit, R.id.iv})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.left_img:
                finish();
                break;
//            case R.id.txt_order:
            case R.id.btn_copy_text:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData abc = cm.getPrimaryClip();
                try {
                    ClipData.Item item = abc.getItemAt(0);
                    String text = item.getText().toString();
                    if (!TextUtils.isEmpty(text)) {
                        txtOrder.setText(text);
                        Toast.makeText(this, "黏贴成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "粘贴板为空", Toast.LENGTH_SHORT).show();
                    }
                } catch (NullPointerException e) {
                    Toast.makeText(this, "粘贴板为空", Toast.LENGTH_SHORT).show();
                }


                break;
            case R.id.take_view:
                selectImage();
                break;
            case R.id.submit:
                uploadImg();
                break;
            case R.id.iv:
                selectImage();
                break;
        }
    }


    public void submitOrder() {

        DealMoneyBean bean = new DealMoneyBean();
        bean.id = item.id;
        bean.money = UI.toString(txtPayMoney);
        bean.outer_notice_sn = UI.toString(txtOrder);
        bean.photo = imgUrl;
        Api.api_service.getConfirm(bean).compose(RxLifeUtil.checkOn(this)).doOnComplete(() -> {
        }).subscribe(result -> {
            Toast.makeText(this, "确认成功", Toast.LENGTH_SHORT).show();
            finish();
        });
    }

    public void uploadImg() {
        if (TextUtils.isEmpty(UI.toString(txtPayMoney))) {
            Toast.makeText(this, "请输入实收金额", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(UI.toString(txtOrder))) {
            Toast.makeText(this, "请输入订单号", Toast.LENGTH_SHORT).show();
            return;
        }

        if (iv.getDrawable() == null) {
            Toast.makeText(this, "请上传凭证", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this).setMessage("确定收款" + UI.toString(txtPayMoney) + "元吗?").setTitle("提示").setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String imgstr = Bitmap2StrByBase64(((BitmapDrawable) iv.getDrawable()).getBitmap());
                UploadImageBean bean = new UploadImageBean();
                bean.img = imgstr;
                Api.api_service.uploadImg(bean).compose(RxLifeUtil.checkOn(TakeMoneySureActivity.this)).doOnComplete(() -> {
                }).subscribe(result -> {
                    imgUrl = result.data.short_url;
                    submitOrder();
                });
                dialog.dismiss();
            }
        }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public static String Bitmap2StrByBase64(Bitmap bit) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
            byte[] bytes = bos.toByteArray();
            return Base64.encode(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
        InputStream input = ac.getContentResolver().openInputStream(uri);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;
        //图片分辨率以480x800为标准
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / ww);
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / hh);
        }
        if (be <= 0)
            be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = ac.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();

        return compressImage(bitmap);//再进行质量压缩
    }

    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = //把ByteArrayInputStream数据生成图片
        return BitmapFactory.decodeStream(isBm, null, null);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x1 && resultCode == -1) {
            if (data != null) {
                takeView.setVisibility(View.GONE);
                try {
                    iv.setImageBitmap(getBitmapFormUri(this, data.getData()));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    @OnClick(R.id.btn_edit)
    public void onViewClicked() {
        txtPayMoney.requestFocus();
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
}
